//
//  ProductsViewController.swift
//  BaseSwift
//
//  Created by gh on 2019/10/12.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit

class ProductsViewController: UIViewController {

    private var lastMenuBtn:UIButton?
    private var classisys:Array<Classisy> = Array()
    private var curClassisy:Classisy?
    private var dataArray:Array<ProductVo> = Array()
    var recomArr:Array<ProductVo> = Array()
    
    var pageMenu: SPPageMenu?

    
    var page = 1
    
    func getClassisy(){
        
        API.playClassisy(params: [:]) { (result) in
            
            self.classisys = result as! Array<Classisy>
            var recClass = Classisy()
            recClass.className = "推荐"
            self.curClassisy = self.classisys.first
            self.classisys.insert(recClass, at: 0)

            self.reloadMapMenus()
            // self.sendRequest()
            
        }
        
    }
    func sendRequest(){
        

        API.playGoods(params: ["classCode":self.curClassisy!.classCode!,
                               "page":page.description]) { (result) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            let pageVo = result as! Page<ProductVo>

            if self.page == 1{
                
                self.dataArray = pageVo.list

            }else{
                
                
                for item in pageVo.list {
                    
                    self.dataArray.append(item)
                }
            
            }
                                
            if pageVo.list.count < 20{
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            self.tableView.reloadData()
        }
        
    }
    
    lazy var tableView:UITableView = {
        
        
        var tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = UIView()
        tableView.separatorColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(UINib.init(nibName: "ProductCell", bundle: nil), forCellReuseIdentifier: "ProductCell")
        tableView.register(UINib.init(nibName: "ProductSmallCell", bundle: nil), forCellReuseIdentifier: "ProductSmallCell")

        return tableView
    }()
    

    lazy var menuBg:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        return bg
        
    }()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        self.navigationView.setTitle("玩家产品")
        self.view.addSubview(self.menuBg)
        let _ = menuBg.sd_layout()?.widthRatioToView(view,1)!.topSpaceToView(view,HT_StatusBarAndNavigationBarHeight)!.heightIs(44)
        self.dataArray = self.recomArr
        self.lastMenuBtn = UIButton()
        self.lastMenuBtn?.tag = 1990
        self.view.addSubview(tableView)
        let _ = tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: HT_StatusBarAndNavigationBarHeight+44, left: 0, bottom: HT_TabbarSafeBottomMargin, right: 0))
        
        
        let header = MJRefreshNormalHeader.init {
            
            self.page = 1

            if self.lastMenuBtn?.tag == 1990{
                
                        API.home_recom_goods(params: [:]) { (result) in
                            
                            self.tableView.mj_header.endRefreshing()
                            self.tableView.mj_footer.endRefreshingWithNoMoreData()

                            let page = result as! Page<ProductVo>
                            self.recomArr = page.list
                            self.tableView.reloadData()

 
                        }
                
            }else{
                
                self.sendRequest()
            }

        }
        header?.stateLabel.isHidden = true
        header?.lastUpdatedTimeLabel.isHidden = true
        self.tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter.init {

            if self.lastMenuBtn?.tag == 1990{
                
                
                                       API.home_recom_goods(params: [:]) { (result) in
                                           
                                        self.tableView.mj_header.endRefreshing()
                                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                                           let page = result as! Page<ProductVo>
                                           self.recomArr = page.list
                                           self.tableView.reloadData()

                
                                       }
                return
            }
            self.page += 1
            self.sendRequest()
        }
        self.tableView.mj_footer = footer
        
        self.getClassisy()
    }
    
    func reloadMapMenus(){
        
        //
        /*let scrMenuBg = UIScrollView()
        self.menuBg.addSubview(scrMenuBg)
        scrMenuBg.backgroundColor = UIColor.white
        let _ = scrMenuBg.sd_layout()?.widthRatioToView(menuBg,1)!.heightIs(44)!.topSpaceToView(menuBg,0)
        for index in 0 ..< self.classisys.count{
            
            let mod = self.classisys.get(at: index)
            
            let menuBtn = UIButton()
            menuBtn.tag  = 1990+index
            menuBtn.addTarget(self, action: #selector(topMenuClick), for: .touchUpInside)
            menuBtn.frame = CGRect(x: index*135, y: 0, width: 135, height: 42)
            menuBtn.setTitle(mod?.className, for: .normal)
            menuBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.2))
            menuBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            scrMenuBg.addSubview(menuBtn)
            scrMenuBg.setupAutoContentSize(withRightView: menuBtn, rightMargin: 0)
            scrMenuBg.showsHorizontalScrollIndicator = false
            
            let icon = UIImageView()
            menuBtn.addSubview(icon)
            icon.backgroundColor = UIColor.GP_Orange_Color
            
            
            icon.tag = 8787
            icon.isHidden = true
            
            
            let _ = icon.sd_layout()?.widthIs(36)!.heightIs(4)!.bottomSpaceToView(menuBtn,6)?.centerXEqualToView(menuBtn)
            icon.sd_width = CGFloat(15*(mod?.className?.count)!)

            
            
            
            if index==0 {
                
                icon.isHidden = false
                self.lastMenuBtn = menuBtn
                menuBtn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
                menuBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))


            }
        }*/
        
        var tits = Array<String>()
        for item in self.classisys {
            
            tits.append(item.className!)
        }
        pageMenu = SPPageMenu.init(frame: CGRect(x: 0, y: HT_StatusBarAndNavigationBarHeight, width: KScreenWidth, height: 45), trackerStyle: .line)
        pageMenu?.setItems(tits, selectedItemIndex: 0)
        pageMenu?.unSelectedItemTitleColor = UIColor.tabbarDefaultTextColor
        pageMenu?.selectedItemTitleColor = UIColor.textTitleColorBlack
        //pageMenu?.selectedItemZoomScale = 1.2
        pageMenu?.selectedItemTitleFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        pageMenu?.unSelectedItemTitleFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.2))
        pageMenu?.delegate = self
        pageMenu?.permutationWay = .scrollAdaptContent
        pageMenu?.spacing = 60
        pageMenu?.trackerWidth = 36
        pageMenu?.tracker.backgroundColor = UIColor.GP_Orange_Color
        pageMenu?.dividingLineHeight = 0
        self.view.addSubview(pageMenu!)
        
    }
    @objc func topMenuClick(btn:UIButton){
        
        btn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        let icon = btn.viewWithTag(8787) as! UIImageView
        icon.isHidden = false
        icon.sd_width = CGFloat(15*(btn.titleLabel?.text!.count)!)

        
        if btn.tag - 1990 == 0 {
            
            self.dataArray = self.recomArr
            tableView.separatorColor = UIColor.clear
            self.tableView.reloadData()
            
        }else{
            
            tableView.separatorColor = UIColor.lineColor
            self.curClassisy = self.classisys.get(at: btn.tag - 1990)
            sendRequest()
        }

        if lastMenuBtn != btn {
            
            self.lastMenuBtn!.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            self.lastMenuBtn!.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.2))
            let icon = lastMenuBtn!.viewWithTag(8787) as! UIImageView
            icon.isHidden = true
        }
        
        lastMenuBtn = btn
        
    }


}
extension ProductsViewController:UITableViewDelegate,UITableViewDataSource,SPPageMenuDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        

        if pageMenu?.selectedItemIndex == 0 {
//
//            let mod = self.dataArray.get(at: indexPath.row)
//            let nameHei = Int((mod?.pdtName?.replacingOccurrences(of: "#", with: " ").stringHeightWith(fontSize: 18, width: KScreenWidth-32))!)
//
//            //300-180
//            let aa = 120+nameHei-22
            return 135+(KScreenWidth-20)*9/16

        }else{
            
            return 150

        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if pageMenu?.selectedItemIndex == 0{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as! ProductCell
            cell.setModel(mod: (self.dataArray.get(at: indexPath.row))!)
            return cell
            
        }else{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProductSmallCell") as! ProductSmallCell
            cell.setModel(mod: (self.dataArray.get(at: indexPath.row))!)
            return cell
        }

    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let mod = self.dataArray.get(at: indexPath.row)
        API.playDetail(params: ["id":(mod?.id)!]) { (result) in
            
            API.productCommentList(params: ["page":"1",
                                            "pdtId":(mod?.id!)!]) { (pageVo) in
                
                                                
                                                let page = pageVo as! Page<CommentVo>
                                                let dvc = ProductDetailVC()
                                                dvc.product = (result as! ProductVo)
                                                if page.list.count > 0{
                                                    
                                                    dvc.commentVo = page.list.first
                                                }
                                                PUSH(from: self, to: dvc)
            }
            

        }
        

    }
    
    func pageMenu(_ pageMenu: SPPageMenu, itemSelectedAt index: Int) {
        
        print(index.description)

        
        if index == 0 {
            
            self.dataArray = self.recomArr
            tableView.separatorColor = UIColor.clear
            self.tableView.reloadData()
            
        }else{
            
            tableView.separatorColor = UIColor.lineColor
            self.curClassisy = self.classisys.get(at: index)
            sendRequest()
        }

    }

}
